<?php
class SitemapAction extends CommonAction {
	private $xmlSize  = 30000; //每个xml的条数

	/*
	<?xml version="1.0" encoding="utf-8"?>
<!-- XML文件需以utf-8编码-->
<sitemapindex>
<!--必填，以 <sitemapindex> 开始标记作为开始，以 </sitemapindex> 结束标记作为结束-->
    <sitemap>
        <!--必填，以<sitemap>标签提交一个子sitemap文件-->
        <loc>http://example.com/ext/xmlsitemap/add/201201/index_20120106.xml</loc>
        <!--必填，识别sitemap的位置-->
        <lastmod>2009-12-14</lastmod>
        <!--选填，识别相对sitemap文件的修改时间-->

    </sitemap>

    <!--必填，标签闭合-->

</sitemapindex>

<!--必填，标签闭合-->
	*/
	
	public function index(){
		$time = date('Y-m-d', NOW_TIME);
		$xml  = '<?xml version="1.0" encoding="utf-8"?>';
		$xml .= '<sitemapindex>';
		
		//首页 + 栏目
		$xml .= '<sitemap><loc>'.$this->webConfig['host_url'].'spidersitemap/index.xml</loc><lastmod>'.$time.'</lastmod></sitemap>';
		
		//文章
		if($count = M('News')->where(array('status'=>1))->count()){
			$pageCount = ceil($count/$this->xmlSize);
			if($pageCount > 1){
				for($i = 1; $i <= $pageCount; $i++){
					$xml .= '<sitemap><loc>'.$this->webConfig['host_url'].'spidersitemap/news'.$i.'.xml</loc><lastmod>'.$time.'</lastmod></sitemap>';
				}
			}else{
				$xml .= '<sitemap><loc>'.$this->webConfig['host_url'].'spidersitemap/news.xml</loc><lastmod>'.$time.'</lastmod></sitemap>';	
			}
		}
		
		//网站
		if($count = M('Websites')->where(array('status'=>1))->count()){
			$pageCount = ceil($count/$this->xmlSize);
			if($pageCount > 1){
				for($i = 1; $i <= $pageCount; $i++){
					$xml .= '<sitemap><loc>'.$this->webConfig['host_url'].'spidersitemap/websites'.$i.'.xml</loc><lastmod>'.$time.'</lastmod></sitemap>';
				}
			}else{
				$xml .= '<sitemap><loc>'.$this->webConfig['host_url'].'spidersitemap/websites.xml</loc><lastmod>'.$time.'</lastmod></sitemap>';	
			}
		}
		
		$xml .= '</sitemapindex>';//end sitemap
		
		header("Content-Type: application/xml;");
		exit($xml);
	}
	
	/**
	* 解析模型路由url
	*/
	private function __parseRuteUrl($type, $modelRute, $modelName, $data, $classIdKey = ''){
		$url = parseRuteUrl($type, $modelRute, $modelName, $data, $classIdKey);
		return 'http://'.$_SERVER['HTTP_HOST'] .$url;
	}
	
	/**
		首页 1.0  栏目页面 0.8  稍微重要的 0.5  内页 0.2
		更新xml
		使用方法： localhost/Sitemap/buildSitemap/t/tag/in/0/k/0.html
		param @in 生成文件的index标识
		param @k  自动循环的key起始位置
	*/
	public function buildSitemap(){
		if('.xml' != substr(__SELF__, strrpos(__SELF__, '.'))){
			$this->go404();
		}
		
		$buildType = I('t', '');
		$buildTypeCate = I('c', '');
		$buildTypes = array('index', 'news', 'websites');
		//当前时间
		$nowTime = NOW_TIME;
	
		/*初始化 xml*/
		$xml = $txt = '';
		$xml .='<?xml version="1.0" encoding="UTF-8" ?>';
		$xml .='<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"';
		$xml .=' xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/">';
		
		if(!in_array($buildType, $buildTypes)){
			$page = str_replace($buildTypes, '', $buildType);
			if($page > 0){
				$buildType = str_replace($page, '', $buildType);
			}
		}
		
		if($buildType == 'index'){ //生成主页和文章分类
			$xml .= $this->joinXml(array($this->webConfig['host_url']), '', 'daily', '1.0', true);
			
			//获取所有文章分类
			if($cate = D('NewsCate')->getAllCate()){
				$cateUrlList = array();
				foreach($cate as $ck=>$cv){
					$cateUrlList[] = $cv['url'];
				}
				$xml .= $this->joinXml($cateUrlList, '', 'daily', '0.8', true);
			}
			
			//获取所有商品分类
			if($cate = D('WebsitesCate')->getAllCate()){
				$cateUrlList = array();
				foreach($cate as $ck=>$cv){
					$cateUrlList[] = $cv['url'];
				}
				$xml .= $this->joinXml($cateUrlList, '', 'daily', '0.8', true);
			}
			
			$xml .= $this->joinXml(array('url'=>U('/websites/')), '', 'daily', '0.8', true);
			$xml .= $this->joinXml(array('url'=>U('/news/')), '', 'daily', '0.8', true);
			
			$this->echoXml($xml);
			return true;
		}
		
		if($buildType == 'news'){ //生成文章.文章多了的时候要做成分页
			$modelObject = M('News');
			if($page > 0){
				$list = $modelObject->getPageList(array('status'=>1), $page, $this->xmlSize);
			}else{
				$list = $modelObject->getAll(array('status'=>1));
			}
			
			foreach($list as $key=>$val){
				$list[$key]['url'] = setViewUrl('article', $val);
			}
			if($list){
				$xml .= $this->joinXml($list, 'url', 'weekly', '0.5', true);
				$this->echoXml($xml);
				return true;
			}
		}
		
		
		
		if($buildType == 'websites'){
			$modelObject = M('Websites');
			if($page > 0){
				$list = $modelObject->getPageList(array('status'=>1), $page, $this->xmlSize);
			}else{
				$list = $modelObject->getAll(array('status'=>1));
			}
			
			foreach($list as $key=>$val){
				$list[$key]['url'] = setViewUrl('site', $val);
			}
			if($list){
				$xml .= $this->joinXml($list, 'url', 'weekly', '0.5', true);
				$this->echoXml($xml);
				return true;
			}
		}
	}
	
	private function joinXml($datas, $urlKey = '', $changefreq = 'daily', $priority = '0.5', $mobile = false){
		$xml ='';
		foreach($datas as $tv){
			$xml .='<url>';
			$tv = empty($urlKey) ? $tv : $tv[$urlKey];
			$xml .='<loc>'.$tv.'</loc>';
			if($mobile){
				$xml .='<mobile:mobile type="autoadapt"/>';
			}
			$xml .='<lastmod>'.date('Y-m-d',NOW_TIME).'</lastmod>';
			$xml .='<changefreq>'.$changefreq.'</changefreq>';
			$xml .='<priority>'.$priority.'</priority>';
			$xml .='</url>';
		}	
		
		return $xml;
	}
	
	private function saveXml($xml, $type){
		$uploadPath = C('TMPL_PARSE_STRING.__SITEMAP__');
		$xml .='</urlset>';
		file_put_contents('.'.$uploadPath.$type.'.xml',$xml);	
	}
	
	private function echoXml($xml){
		$xml .='</urlset>';
		header("Content-Type: application/xml;");
		echo $xml;
	}
	
	private function joinTxt($datas, $urlKey = ''){
		$txt ='';
		foreach($datas as $tv){
			$tv = empty($urlKey) ? $tv : $tv[$urlKey];
			$txt .= $tv.PHP_EOL;
		}	
		return $txt;
	}
	
	private function saveTxt($txt, $saveName){
		$uploadPath = C('TMPL_PARSE_STRING.__SITEMAP__');
		
		file_put_contents('.'.$uploadPath.$saveName.'.txt',$txt);	
	}
}//end class